from rabbitmq_operator import rabbit_conn
import json
from handle_db import init_insert_order
from redis_operator import enter_order_queue

import time


# 下面定义对应的订单消费者，
# 监听订单队列
# 只要存在消息就读出,然后写入mysql订单历史
# 此时交易未成交 所以交易状态是未完成


def insert_init_order(ch, method, properties, body):
    body = json.loads(body)
    print("我是回调函数")
    if init_insert_order(body):
        enter_order_queue(body)
        ch.basic_ack(delivery_tag=method.delivery_tag)
    else:
        ch.basic_nack(delivery_tag=method.delivery_tag)


def start_order_consume():
    channel = rabbit_conn.channel()
    exchange = 'order.exchange'
    queue = 'order.queue'
    channel.exchange_declare(exchange=exchange,
                             exchange_type='topic',
                             durable=True)
    channel.queue_declare(queue=queue,
                          durable=True)
    channel.queue_bind(queue=queue, exchange=exchange,
                       routing_key="order." + '*' + '.' + '*' + '.' + '*' \
                                   + '.' + '*' + '.' + '*')
    channel.basic_qos(prefetch_count=1)
    channel.basic_consume(on_message_callback=insert_init_order,
                          queue=queue,
                          auto_ack=False)
    print("我是订单队列的消费者，我要开始消费了")
    channel.start_consuming()


start_order_consume()
